package com.woniu.payservice.job;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.woniu.payservice.entity.Orders;
import com.woniu.payservice.service.OrdersService;
import com.woniu.payservice.util.OrdersStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
/**
 * @Auther: 李浪  <br/>
 * @Date: 2020/3/24:18:33  <br/>
 * @Description:定时退款
 */
@Component
public class RefoundScheduler {
    @Autowired
    public OrdersService ordersService;

    @Autowired
    AlipayClient alipayClient;

    //定时退款
    @Scheduled(cron = "0 0 3 * * ? ")
    public void refound() {
        List<Orders> orders = ordersService.queryOrdersByOrderStatus(OrdersStatus.WAITREFOUND.getI());
        for (Orders order : orders) {
            //设置请求参数
            AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
            //商户订单号，商户网站订单系统中唯一订单号
            String out_trade_no = order.getOrdernumber();
            if (out_trade_no == null) {
                continue;
            }
            //支付宝交易号
            String trade_no = order.getPaynumber();
            //请二选一设置
            //需要退款的金额，该金额不能大于订单金额，必填
            String refund_amount = order.getTotalmoney().toString();
            //退款的原因说明
            String refund_reason = "个人原因";
            //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
            alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                    + "\"trade_no\":\"" + trade_no + "\","
                    + "\"refund_amount\":\"" + refund_amount + "\"}");
            //请求
            String result = null;
            try {
                result = alipayClient.execute(alipayRequest).getBody();
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            System.out.println(result);
            if (result.contains("Success")) {
                //修改数据库
                try {
                    order.setStatus(OrdersStatus.REFOUND.getI());
                    ordersService.updateOstateByOnumber(order);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                //记录日志 退款失败
            }
        }
    }

}
